// Created by Roman Novitsky on 22.04.2009


#region Imported Namespaces


using System;
using System.Collections.Specialized;
using System.Reflection;
using System.Windows.Data;

using WtfManager.Framework;


#endregion


namespace WtfManager.UIManager
{
  public class ServiceDataProvider: ObjectDataProvider
  {
    #region Fields


    private string _propertyName;
    private Type _service;
    private Service _serviceInstance;


    #endregion


    public ServiceDataProvider()
    {
      INotifyCollectionChanged services = WtfFramework.Instance.Services;
      services.CollectionChanged += ServicesCollectionChanged;
    }

    void ServicesCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
      UpdateObjectInstance();
    }


    #region Properties/Indexers


    public string PropertyName
    {
      get
      {
        return _propertyName;
      }
      set
      {
        _propertyName = value;

        UpdateObjectInstance();
      }
    }

    public Type Service
    {
      get
      {
        return _service;
      }
      set
      {
        _service = value;

        UpdateObjectInstance();
      }
    }


    #endregion


    #region Methods


    private void UpdateObjectInstance()
    {
      if (_serviceInstance != null)
      {
        _serviceInstance.StateChanged -= ServiceInstanceIsInitializedChanged;
      }

      if (_service == null)
      {
        return;
      }

      _serviceInstance = WtfFramework.Instance.Services[_service];

      if (_serviceInstance == null)
      {
        return;
      }

      _serviceInstance.StateChanged += ServiceInstanceIsInitializedChanged;

      if(!_serviceInstance.IsInitialized)
        return;

      if (!string.IsNullOrEmpty(_propertyName))
      {
        PropertyInfo propertyInfo = _service.GetProperty(PropertyName);
        ObjectInstance = propertyInfo.GetValue(_serviceInstance, null);

        return;
      }

      ObjectInstance = _serviceInstance;
    }

    void ServiceInstanceIsInitializedChanged(object sender, EventArgs e)
    {
      UpdateObjectInstance();
    }


    #endregion
  }
}